
package com.jf.cloud.im.controller.platform;

import cn.hutool.core.date.DateUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.user.feign.UserFeignClient;
import com.jf.cloud.api.user.vo.UserApiVO;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.im.constants.Admin;
import com.jf.cloud.im.constants.Constant;
import com.jf.cloud.im.constants.SendType;
import com.jf.cloud.im.model.ImMsgBizEmployeeRecent;
import com.jf.cloud.im.model.ImMsgBizUser;
import com.jf.cloud.im.model.ImMsgBizUserHistory;
import com.jf.cloud.im.service.ImMsgBizEmployeeRecentService;
import com.jf.cloud.im.service.ImMsgBizUserHistoryService;
import com.jf.cloud.im.service.ImMsgBizUserService;
import com.jf.cloud.im.vo.ConversationVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author zz
 */
@RestController
@RequestMapping("/p/im")
@Tag(name = "平台聊天接口")
public class SysController {

    @Autowired
    private ImMsgBizEmployeeRecentService imMsgBizEmployeeRecentService;

    @Autowired
    private ImMsgBizUserHistoryService imMsgBizUserHistoryService;
    @Autowired
    private UserFeignClient userFeignClient;

    @PostMapping("/conversations")
    @Operation(summary = "最后的对话信息列表项" , description = "获取最后的对话信息列表项")
    public ResponseEntity<PageVO<ConversationVO>> conversations(PageDTO pageDTO) {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        PageVO<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentPage = imMsgBizEmployeeRecentService.pageBySendTypeAndBizIdAndEmployeeId(pageDTO, SendType.PLATFORM, userInfoInTokenBO.getTenantId(), userInfoInTokenBO.getUserId());
        List<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentList = imMsgBizEmployeeRecentPage.getList();
        List<ConversationVO> conversationList = new ArrayList<>();
        for (ImMsgBizEmployeeRecent imMsgBizEmployeeRecent : imMsgBizEmployeeRecentList) {
//                ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(SendType.SHOP, imMsgBizEmployeeRecent.getBizId(), imMsgBizEmployeeRecent.getUserId());
            ImMsgBizUserHistory imMsgBizUserHistoryParam = new ImMsgBizUserHistory();
            imMsgBizUserHistoryParam.setSendType(SendType.PLATFORM);
            imMsgBizUserHistoryParam.setBizId(imMsgBizEmployeeRecent.getBizId());
            imMsgBizUserHistoryParam.setEmployeeId(imMsgBizEmployeeRecent.getEmployeeId());
            imMsgBizUserHistoryParam.setUserId(imMsgBizEmployeeRecent.getUserId());
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.getByParam(imMsgBizUserHistoryParam);
            ConversationVO conversation = new ConversationVO();
            conversation.setChatType(imMsgBizUserHistory.getSendType());
            conversation.setShopId(imMsgBizEmployeeRecent.getBizId());
            conversation.setUserId(imMsgBizEmployeeRecent.getUserId());
            conversation.setLatestMsg(imMsgBizUserHistory.getContent());
            conversation.setUnread(imMsgBizEmployeeRecent.getEmployeeUnreadNum());
            // todo 东8区，不应该写死"+8"后续优化
            conversation.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant().toEpochMilli());
            conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUserHistory.getCreateTime().toInstant()), "yyyy/MM/dd"));
            conversation.setLatestMsgTime(LocalDateTime.ofInstant(imMsgBizUserHistory.getCreateTime().toInstant(), ZoneId.systemDefault()));
            conversation.setType(imMsgBizUserHistory.getType());
            conversation.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
            ServerResponseEntity<UserApiVO> userResponse = userFeignClient.getInsiderUserData(imMsgBizEmployeeRecent.getUserId());
            if (!userResponse.isSuccess()) {
                throw new LuckException(userResponse.getMsg());
            }
            UserApiVO user = userResponse.getData();
            if (Objects.nonNull(user)) {
                conversation.setPic(user.getPic());
                conversation.setFriendName(user.getNickName());
            } else {
                conversation.setFriendName("*用户已注销*");
            }
            Set<String> set2 = RedisUtil.keys(Constant.ONLINE_USER_PREFIX + conversation.getUserId() + Constant.UNDERLINE + "*");
            if (set2.isEmpty()) {
                conversation.setIsOnline(false);
            } else {
                conversation.setIsOnline(true);
            }
            conversationList.add(conversation);
        }

        PageVO<ConversationVO> conversationPage = new PageVO<>();
        BeanUtils.copyProperties(imMsgBizEmployeeRecentPage, conversationPage);
        conversationPage.setList(conversationList);
        return ResponseEntity.ok(conversationPage);
    }

    @GetMapping("/userInfo")
    @Operation(summary = "获取用户信息" , description = "获取用户信息")
    public ResponseEntity<List<ConversationVO>> userInfo(@ParameterObject Long userId) {
        List<ConversationVO> conversations = new ArrayList<>();
        ServerResponseEntity<UserApiVO> userApiResponse = userFeignClient.getInsiderUserData(userId);
        if (!userApiResponse.isSuccess()) {
            throw new LuckException(userApiResponse.getMsg());
        }
        UserApiVO user = userApiResponse.getData();
        if (Objects.nonNull(user)) {
            ConversationVO conversation = new ConversationVO();
            conversation.setUserId(userId);
            conversation.setFriendName(user.getNickName());
            conversation.setPic(user.getPic());
            conversations.add(conversation);
        }
        return ResponseEntity.ok(conversations);
    }

}
